import java.io.File;
import java.util.ArrayList;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.w3c.dom.Node;
import org.w3c.dom.NodeList;




public class XMLMovieFinder implements IMovieFinder{
	private String filename;
	
	public XMLMovieFinder(){
		this.filename = "movies.xml";
	}
	
	public ArrayList<Movie> findall(){

		ArrayList<Movie> readMovies = new ArrayList<Movie>();	
		
		try {
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); 
		    DocumentBuilder builder = factory.newDocumentBuilder(); 
		    org.w3c.dom.Document document = builder.parse( new File(this.filename) ); 
		    document.getDocumentElement().normalize();
		    
		    //NodeList movieNodes = document.getFirstChild().getChildNodes();
		    NodeList movieNodes = document.getElementsByTagName("movie");
		   
		    
		    for(int i=0; i < movieNodes.getLength(); i++){
		    	
		    	Node tmpMovie = movieNodes.item(i);
		    	NodeList tmpList = tmpMovie.getChildNodes();
		    	
		    	if(tmpMovie.getNodeType() == Node.ELEMENT_NODE){
		    		
		    		Movie newMovie = new Movie();

		    		for(int a=0; a < tmpList.getLength(); a++){
		    			if(tmpList.item(a).getNodeType() == Node.ELEMENT_NODE){
		    				if(tmpList.item(a).getNodeName() == "title"){
		    					newMovie.setTitle(tmpList.item(a).getFirstChild().getNodeValue());
		    				}
		    				else if(tmpList.item(a).getNodeName() == "director"){
		    					newMovie.setDirector(tmpList.item(a).getFirstChild().getNodeValue());
		    				}
		    			}
		    		}
		    		
		    		readMovies.add(newMovie);
		    	}
		    	
		    }
		   
		}catch(Exception e) {
			System.out.println("Fehler beim Lesen aus der XML Datei");
		}

		
		return readMovies;
	}
}
